# -*- coding: UTF-8 -*-

##########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

from flask import Blueprint
from flask import request
import utils.pgsql.pgactivity as pgactivity
import utils.pgsql.pgcase as pgacase
import utils.pgsql.pgdevice as device
from utils.wraps import token, urlcost
import utils.message.response as response
import json
from ast import literal_eval
import utils.pgsql.pgtemplate as template
import requests
import utils.common.log as log

### 活动管理配置
# Active Management Configuration

activity_module = Blueprint(
    "base_activity", __name__, url_prefix="/api/v1/mission/activity"
)


@activity_module.route("/", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def activitys():
  
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    obj = pgactivity.PgActivity()

   
    if userInfo["role"] == 1:
        return response.make_response_success(obj.all())
    elif userInfo["role"] in [2]:
        avtivityInfor = obj.allByOperatorId(userInfo["operatorId"])
        # for i in range(len(avtivityInfor)):
        #     avtivityInfor[i]["deviceIds"] = literal_eval(
        #         avtivityInfor[i]["deviceIds"])
        #     avtivityInfor[i]["caseName"] = pgacase.PgCase(
        #     ).get_caseName(avtivityInfor[i]['caseId']).get("caseName")
        return response.make_response_success(avtivityInfor)
    elif userInfo["role"] in [3]:
        avtivityInfor = obj.allByCaseId(userInfo["caseId"])
        # for i in range(len(avtivityInfor)):
        #     avtivityInfor[i]["deviceIds"] = literal_eval(
        #         avtivityInfor[i]["deviceIds"])
        return response.make_response_success(avtivityInfor)
    else:
        return response.make_response_401()


@activity_module.route("/case/<int:caseId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def activityscaseId(caseId):
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    obj = pgactivity.PgActivity()
    playground_limit = userInfo["playground_limit"] if userInfo['role'] == 3 else ""
    avtivityInfor = obj.allByCaseId(caseId, playground_limit)
    return response.make_response_success(avtivityInfor)

 
@activity_module.route("/activityall/", methods=["GET"])
@urlcost.cost_count_wraps
def activity_all():
 

    obj = pgactivity.PgActivity()
    res = obj.all()
    print(res)
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()


 
@activity_module.route("/case/activityall/<int:caseId>", methods=["GET"])
@urlcost.cost_count_wraps
def activity_case_all(caseId):
 

    obj = pgactivity.PgActivity()
    res =  obj.allByCaseId(caseId)
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()



@activity_module.route("/", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def activity_add():
   
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    obj = pgactivity.PgActivity()
    dic = json.loads(request.data)
    if obj.activityNameget(dic["activityName"], dic["caseId"]) != []:
        return response.make_response_1505()

    if len(obj.activitycaseget(dic["caseId"])) > 99:
        return response.make_response_1512()

    if userInfo["role"] in [1, 2, 3]:
        ret = obj.add(dic)
        if ret:
            return response.make_response_success_no_data()
        else:
            return response.make_response_1505()

    else:
        return response.make_response_401()


@activity_module.route("/<int:activityId>", methods=["PUT", "GET", "DELETE"])
@token.login_required
@urlcost.cost_count_wraps
def funactivity(activityId):
  
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2, 3]:
        if request.method == "PUT":   
            obj = pgactivity.PgActivity()
            dic = json.loads(request.data)
            # activityName 校验
            if (
                obj.activityNameeditget(dic["activityName"], dic["caseId"], activityId)
                != []
            ):
                return response.make_response_1505()
            ret = obj.modify(activityId, dic)
            if ret:
                return response.make_response_success_no_data()
            else:
                return response.make_response_1000()
        elif request.method == "GET":   
            obj = pgactivity.PgActivity()
            return response.make_response_success(obj.get(activityId))
        elif request.method == "DELETE":   
            obj = pgactivity.PgActivity()
            if obj.delete(activityId):
                return response.make_response_success_no_data()
            else:
                return response.make_response_1000()
    else:
        return response.make_response_401()



# 主动推送活动下的模板数据
@activity_module.route("/template_to_AI", methods=["POST"])
def template_to_AI():
    retdic ="ok"
    # 查询所有未推送模板  的活动
    tips = [] # 前端页面给提示，同步了哪些信息
    obj = pgactivity.PgActivity()
    dic = json.loads(request.data)
    caseId = dic.get("caseId","")
    all_notsyn_Activity_list = obj.notsyn_Activity(caseId)
    # 遍历每一个活动数据
    for one_Activity_dict in all_notsyn_Activity_list:
        tip = {}
        ActivityId_str = one_Activity_dict.get("activityId","")
        activityName_str = one_Activity_dict.get("activityName","")
        templateId_str = one_Activity_dict.get("templateId","")
        faceNum_int = one_Activity_dict.get("faceNum","")
        videoConfigList_dic = one_Activity_dict.get("videoConfigList","")
        ai_ip = one_Activity_dict.get("ai_ip","")
        # 根据  模板id 查询对应的模板数据
        tem_obj = template.PgTemplate()
        templateId_data = tem_obj.get_templateId_data(templateId_str)
        # 校验查询结果

        # print("模板数据：",type(templateId_data),templateId_data) # dict
        send_template_str = templateId_data.get("templateData",{})
        ticketPrice_str = templateId_data.get("ticketPrice",1)
        templateId_str = templateId_data.get("templateId","")
        # print("send_template_str:",send_template_str)

        send_template_dic =eval(send_template_str)
        log.logging.info("send_template_dic:" + str(send_template_dic))
        # print("send_template_dic", type(send_template_dic), send_template_dic)

        # 判断查询结果是否存在
        if not videoConfigList_dic:

            return response.make_response_405()
        else:
            GBcode = videoConfigList_dic.get("VideoCfg")[0].get("DeviceIds")[0]
            # print("GBcode", GBcode)
            # 根据 GBcode 查询 groupid
            device_obj = device.PgDevice()
            #
            groupld_str = device_obj.GBcode_select_groupld(GBcode)
            # print("groupld_str",groupld_str)
            if not groupld_str:
                return response.make_response_406("查询groupld失败",406)
            effects_list =[]
            send_template_dic["bgmDuration"] = send_template_dic.get("BgmDuration","")
            send_template_dic["bgmPath"] = send_template_dic.get("BgmPath","")
            send_template_dic["groupId"] = groupld_str.get("groupId","")
            send_template_dic["deviceId"] = groupld_str.get("deviceId","")
            send_template_dic["videoTemplate"] = send_template_dic.get("VideoTemplate","")
            send_template_dic["faceNum"] = faceNum_int
            send_template_dic["ticketPrice"] = ticketPrice_str
            send_template_dic["activityId"] = ActivityId_str
            send_template_dic["activityName"] = activityName_str
            send_template_dic["templateId"] = templateId_str
            send_template_dic["templateName"] = activityName_str


            del send_template_dic["BgmDuration"]
            del send_template_dic["BgmPath"]
            del send_template_dic["VideoTemplate"]

            VideoTemplate_list_new = []
            # 键转换 将字典中的所有键转换成驼峰
            VideoTemplate_list = send_template_dic.get("videoTemplate")
            log.logging.info("VideoTemplate_list:" + str(VideoTemplate_list))
            for one_dic in VideoTemplate_list:
                log.logging.info("one_dic111:" + str(one_dic))
                one_dic_key_list = one_dic.keys()
                for one_key in list(one_dic_key_list):
                    if one_key =="VideoID":
                        one_dic["videoSort"] =one_dic["VideoID"]

                    new_key = one_key[0].lower() + one_key[1:]

                    one_dic[new_key] = one_dic[one_key]
                    del one_dic[one_key]
                if one_dic["videoType"] == "template":
                    VideoTemplate_list_new.append(one_dic)
                # 获取人脸片段中的特效

                elif one_dic["videoType"] == "fragment":
                    VideoEffects_list  = one_dic.get("videoEffects")
                    log.logging.info("videoEffects" +str(VideoEffects_list))
                    one_effects_list =[]
                    if not VideoEffects_list:
                        # one_effects_list.append("none")
                        effects_list.append("none")
                    else:
                        for one_Label_dic in VideoEffects_list:
                            Label_str = one_Label_dic.get("Label","none")
                            # one_effects_list.append(Label_str)
                            effects_list.append(Label_str)


        send_template_dic["videoTemplate"] = VideoTemplate_list_new
        send_template_dic["effects"] = effects_list
        if send_template_dic:
            # print("推送模板数据：",send_template_dic)
            log.logging.info(json.dumps(send_template_dic))
            # 发送数据给AI
            # Stream_url = "http://119.45.238.18:7070"  # 第一套
            # Stream_url = "http://175.27.245.122:7070"  # 第二套
            # Stream_url = "http://146.56.244.220:7070"    # 第三套
            # Stream_url = "http://118.195.226.96:7070"    # 第四套
            # Stream_url = "http://118.195.136.98:7070"    # 第五套
            # Stream_url = "http://146.56.237.33:7070"    # 第六套
            Stream_url = f"http://{ai_ip.strip()}:7070"
            log.logging.info(Stream_url)
            url = Stream_url + "/api/aip/slices/groupTemplateSync"
            header = {
                "content-type": "application/json",
                "Authorization": "ZTAI5t7StH4JsKGysZfb2XgT",
            }

            try:
                tip['request_data'] = send_template_dic
                ret = requests.post(url, headers=header, data=json.dumps(send_template_dic), verify=False)

                retdic = json.loads(ret.text)
                tip['res'] = retdic
                # print("主动推送模板数据响应", retdic) #{'timestamp': '2023-04-14T05:59:20.244+00:00', 'status': 400, 'error': 'Bad Request', 'message': '', 'path': '/api/aip/slices/groupTemplateSync'}
                log.logging.info(str(retdic))
            except Exception as e:
                return response.make_response_406("请求失败", 406)
            status_num = retdic.get("code",0)
            if status_num in [200,"200"]:

                # 将 活动状态改为 1
                update_Activity_synState = obj.update_Activity_synState_sql(ActivityId_str)
                tips.append(tip)


    return response.make_response_406(tips,200)
